package com.gewu.pm.ui.adapter.delivery;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.gewu.pm.R;
import com.gewu.pm.app.AppAdapter;
import com.gewu.pm.ui.activity.delivery.DeliveryGoodsDetailActivity;

/**
 * 配送终端列表适配器
 */
public class DeliveryTerminalAdapter extends AppAdapter<String> {
    Context context;

    public DeliveryTerminalAdapter(Context context) {
        super(context);
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder();
    }

    private final class ItemViewHolder extends AppAdapter<?>.ViewHolder {

        private final TextView mTerminalNameView;
        private final ImageView mNavigationIcon;
        private final TextView tvProductDetails;

        private ItemViewHolder() {
            super(R.layout.delivery_terminal_item);
            mTerminalNameView = findViewById(R.id.tv_terminal_name);
            mNavigationIcon = findViewById(R.id.iv_navigation);
            tvProductDetails = findViewById(R.id.tv_product_details);

            // 导航图标点击事件（直接在Adapter中处理）
            mNavigationIcon.setOnClickListener(v -> {
                openNavigation();
            });
            // 商品详情点击事件
            tvProductDetails.setOnClickListener(view -> {
                DeliveryGoodsDetailActivity.start(getContext());
            });
        }

        @Override
        public void onBindView(int position) {
            String terminalName = getItem(position);

            // 设置终端名称
            mTerminalNameView.setText(terminalName);
        }

        /**
         * 打开地图导航
         */
        private void openNavigation() {
            // 使用布局中写死的地址
            String address = "伟业路298号（伟业地铁站A口步行460米）";

            try {
                // 打开系统地图导航
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("geo:0,0?q=" + address));

                if (intent.resolveActivity(getContext().getPackageManager()) != null) {
                    getContext().startActivity(intent);
                } else {
                    Toast.makeText(context, "无法打开地图导航", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                Toast.makeText(context, "无法打开地图导航", Toast.LENGTH_LONG).show();
            }
        }
    }
}

